<template>
  <div>
    <!-- 头部面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- card卡片区  用于展示用户列表 -->
    <el-card>
      <!-- 头部提示区 -->
      <el-alert show-icon :closable="false" title="注意:只允许为第三级分类设置相关参数" type="warning"></el-alert>
      <!-- 级联选择框 -->
      <el-row class="rowMargin">
        <el-col>
          <span>选择商品分类:</span>
          <el-cascader
            v-model="selectKeys"
            :options="cateList"
            :props="cascaderProps"
            @change="handleCascaderChange"
            expand-trigger="hover"
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- tabs标签页 -->
      <el-tabs v-model="activeName" @tab-click="handleTabsClick">
        <!-- 动态参数 -->
        <el-tab-pane label="动态参数" name="many">
          <!-- <el-button type="primary" :disabled="isDisabled" @click="addDialogVisible=true">添加参数</el-button>
          <el-table :data="manyList" border stripe style="width: 100%">
            <el-table-column type="expand">
              <template v-slot="scope">
                <el-tag
                  closable
                  v-for="(item,index) in scope.row.attr_vals"
                  :key="index"
                  @close="closeTag(index,scope.row)"
                >{{item}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column label="操作">
              <template v-slot="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  @click="showEditInfo(scope.row.attr_id)"
                >编辑</el-button>
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  @click="deleteParams(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>-->
        </el-tab-pane>
        <!-- 静态属性 -->
        <el-tab-pane label="静态属性" name="only">
          <!-- <el-button type="primary" :disabled="isDisabled" @click="addDialogVisible=true">添加属性</el-button>
          <el-table :data="onlyList" border stripe style="width: 100%">
            <el-table-column type="expand">
              <template v-slot="scope">
                <el-tag closable v-for="(item,index) in scope.row.attr_vals" :key="index">{{item}}</el-tag>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column prop="attr_name" label="属性名称"></el-table-column>
            <el-table-column label="操作">
              <template v-slot="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  @click="showEditInfo(scope.row.attr_id)"
                >编辑</el-button>
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  @click="deleteParams(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>-->
        </el-tab-pane>

        <!-- 动态参数与静态属性 数据展示 -->
        <div>
          <el-button
            type="primary"
            :disabled="isDisabled"
            @click="addDialogVisible=true"
          >{{activeName==='only'?'添加属性':'添加参数'}}</el-button>
          <el-table :data="tabelData" border stripe style="width: 100%">
            <el-table-column type="expand">
              <template v-slot="scope">
                <el-tag
                  closable
                  v-for="(item,index) in scope.row.attr_vals"
                  :key="index"
                  @close="closeTag(index,scope.row)"
                >{{item}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column prop="attr_name" :label="activeName==='only'?'属性名称':'参数名称'"></el-table-column>
            <el-table-column label="操作">
              <template v-slot="scope">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  @click="showEditInfo(scope.row.attr_id)"
                >编辑</el-button>
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  @click="deleteParams(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tabs>

      <!-- 添加动态参数、静态属性对话框  共用一个 -->
      <el-dialog
        :title="'添加'+titleText"
        :visible.sync="addDialogVisible"
        width="30%"
        @close="closeAddDialogVisible"
      >
        <el-form
          :model="addForm"
          :rules="addFormRules"
          ref="addFormRef"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item :label="titleText" prop="attr_name">
            <el-input v-model="addForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveAddParams">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 修改动态参数、静态属性的对话框 -->
      <el-dialog
        :title="'修改'+titleText"
        :visible.sync="editDialogVisible"
        width="30%"
        @close="closeeditDialogVisible"
      >
        <el-form
          :model="editForm"
          :rules="editFormRules"
          ref="editFormRef"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item :label="titleText" prop="attr_name">
            <el-input v-model="editForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="saveeditParams">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>
<script>
export default {
  data() {
    return {
      cateList: [], // 获取分类列表
      selectKeys: [], // 获取选择的分类id
      cascaderProps: {
        expandTrigger: 'hover',
        label: 'cat_name',
        value: 'cat_id',
        children: 'children'
      },
      activeName: 'many', // v-model双向绑定 默认选中第一个tab栏标签
      // onlyList: [], // 获取到的静态属性的数据列表
      // manyList: [], // 获取到的动态参数的数据列表
      tabelData: [],
      addDialogVisible: false,
      addForm: {
        attr_name: ''
      },
      addFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      },
      editDialogVisible: false,
      editForm: {
        attr_name: ''
      },
      editFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      },
      attrId: ''
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    async getCateList() {
      const res = await this.$http.get('categories')
      //   console.log(res)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.cateList = res.data
    },
    handleCascaderChange() {
      //   console.log(this.selectKeys)
      // 当级联选择框发生变化，调用请求，重新加载数据
      this.getParamsInfo()
    },
    // 获取选中的tab栏 双向数据绑定，当tab栏切换的时候，会返回选中tab栏的name值
    handleTabsClick() {
      //   console.log(this.activeName)
      //   当tab栏切换的时候需要重新调用请求，加载数据
      this.getParamsInfo()
    },
    // 发送请求获取参数数据
    async getParamsInfo() {
      // 如果用户选择的不是三级分类
      if (this.selectKeys.length !== 3) {
        this.selectKeys = []
        this.tabelData = []
        return null
      } else {
        //   用户选择了三级分类  发送请求，渲染动态参数或静态属性列表
        const res = await this.$http.get(
          `categories/${this.cateID}/attributes`,
          { params: { sel: this.activeName } }
        )
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        res.data.forEach(item => {
          //   为每一个item添加自定义属性，控制文本框的显示与隐藏并获取文本框的值
          item.inputVisible = false // 控制输入框的显示与隐藏
          item.inputValue = '' // 双向数据绑定，获取输入框的内容
          if (item.attr_vals.trim().length > 0) {
            return (item.attr_vals = item.attr_vals.split(' '))
          } else {
            return (item.attr_vals = [])
          }
        }) // 将attr_vals从字符串转为数组
        // console.log(res.data)
        // if (this.activeName === 'only') {
        //   this.onlyList = res.data
        // } else {
        //   this.manyList = res.data
        // }
        console.log(res)
        this.tabelData = res.data
      }
    },
    // 关闭添加参数对话框
    closeAddDialogVisible() {
      this.$refs.addFormRef.resetFields()
    },
    // 保存添加的参数
    saveAddParams() {
      // 验证表单
      this.$refs.addFormRef.validate(async val => {
        if (!val) return // 验证失败
        // 验证成功，发送请求添加参数
        const res = await this.$http.post(
          `categories/${this.cateID}/attributes`,
          { attr_name: this.addForm.attr_name, attr_sel: this.activeName }
        )
        console.log(res)
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.getParamsInfo()
        this.addDialogVisible = false
      })
    },
    // 关闭修改的规划矿
    closeeditDialogVisible() {
      this.$refs.editFormRef.resetFields()
    },
    // 展示要修改的数据参数
    async showEditInfo(id) {
      //   console.log(id)
      // 根据参数id发送请求，获取要修改的参数信息
      const res = await this.$http.get(
        `categories/${this.cateID}/attributes/${id}`,
        { params: this.activeName }
      )
      //   console.log(res)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      // 获取成功
      this.editForm.attr_name = res.data.attr_name
      this.attrId = res.data.attr_id
      this.editDialogVisible = true
    },
    // 保存修改的参数
    saveeditParams() {
      //   验证是否符合规则
      this.$refs.editFormRef.validate(async val => {
        if (!val) return
        // 验证成功
        const result = await this.$http.put(
          `categories/${this.cateID}/attributes/${this.attrId}`,
          { attr_name: this.editForm.attr_name, attr_sel: this.activeName }
        )
        console.log(result)
        if (result.meta.status !== 200) {
          return this.$message.error(result.meta.msg)
        }

        // 请求成功
        this.$message.success(result.meta.msg)
        this.getParamsInfo() // 重新加载数据
        this.editDialogVisible = false
      })
    },
    // 删除参数
    async deleteParams(attrID) {
      // 确认是否确认删除
      const result = await this.$confirm(
        '此操作将永久删除该参数, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      if (result !== 'confirm') {
        return this.$message.info('您已取消删除操作')
      }
      // 确认删除  发送请求删除
      const res = await this.$http.delete(
        `categories/${this.cateID}/attributes/${attrID}`
      )
      //   console.log(res)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.getParamsInfo()
    },
    // 当输入框keyup或blur时触发，获取展示框中输入的文本内容
    handleInputConfirm(row) {
      // 如果用户没有输入内容
      if (row.inputValue.trim().length === 0) {
        row.inputVisible = false
        row.inputValue = ''
        return
      }
      //   用户输入了内容后
      row.attr_vals.push(row.inputValue)
      row.inputValue = ''
      row.inputVisible = false
      this.getAttrInfo(row)
    },
    // 当点击button的时候，显示input输入框
    showInput(row) {
      row.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    async getAttrInfo(row) {
      //   将更改的参数数据保存到数据库中 发送请求
      const res = await this.$http.put(
        `categories/${this.cateID}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: this.activeName,
          attr_vals: row.attr_vals.join(' ')
        }
      )
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error('更新参数失败')
      this.$message.success(res.meta.msg)
    },
    // 删除tag参数
    async closeTag(index, row) {
      console.log(index, row)
      // 询问是否确认删除
      const result = await this.$confirm(
        '此操作将永久删除该参数, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      if (result !== 'confirm') return this.$message.info('已取消删除')
      row.attr_vals.splice(index, 1)
      this.getAttrInfo(row)
    }
  },
  // 计算属性，得到级联选择框的长度，控制tabs标签是否禁用
  computed: {
    //   判断按钮是否禁用
    isDisabled() {
      if (this.selectKeys.length !== 3) {
        return true // 如果选择的不是在三级分类层面，就让tabs标签页禁用
      }
      return false
    },
    // 获取分类的id
    cateID() {
      // 获取所有分类的三级分类id
      if (this.selectKeys.length !== 3) {
        return null
      }
      return this.selectKeys[2] // 将选择的数组id，最后一个return出去
    },
    // 根据点击的是only还是many控制对话框的显示
    titleText() {
      if (this.activeName === 'only') {
        return '静态属性'
      } else {
        return '动态参数'
      }
    }
  }
}
</script>
<style lang="less" scoped>
.rowMargin {
  margin: 15px 0;
}
.el-tag {
  margin: 0 10px;
}
.input-new-tag {
  width: 120px;
}
</style>
